using System.Collections.Generic;

namespace IQIGame.Onigao.Framework
{
    public interface IBetterPrioritizElement
    {
        public int priority { get; }
    }
    public class BetterPrioritizeList<T> : List<T> where T : IBetterPrioritizElement
    {
        public virtual bool euqalAddToLast { get; } = false;

        public BetterPrioritizeList()
        {
        }

        public BetterPrioritizeList(int cap) : base(cap)
        {
        }

        public BetterPrioritizeList(IEnumerable<T> collection) : base(collection)
        {
        }

        public virtual int AddByPriority(T element)
        {
            // 按照priority优先级从小到大拆入
            int insertIndex = -1;
            for (int i = 0; i < this.Count; i++)
            {
                var r = this[i];
                if (element.priority <= r.priority)
                {
                    this.Insert(i, element);
                    insertIndex = i;
                    break;
                }
            }
            if (insertIndex == -1)
            {
                insertIndex = this.Count;
                this.Add(element);
            }
            return insertIndex;
        }

        public int RemoveGetIndex(T element)
        {
            int num = IndexOf(element);
            if (num >= 0)
            {
                RemoveAt(num);
                return num;
            }

            return num;
        }

        /// <summary>
        /// 获取最优先的item
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool TryGetPrioritizeItem(out T item)
        {
            if (this.Count > 0)
            {
                item = this[this.Count - 1];
                return true;
            }
            item = default;
            return false;
        }

    }

    public class BetterPrioritizeEqualLastList<T> : BetterPrioritizeList<T> where T : IBetterPrioritizElement
    {
        public override bool euqalAddToLast { get; } = true;

        public BetterPrioritizeEqualLastList()
        {
        }

        public BetterPrioritizeEqualLastList(int cap) : base(cap)
        {
        }

        public BetterPrioritizeEqualLastList(IEnumerable<T> collection) : base(collection)
        {
        }

        public override int AddByPriority(T element)
        {
            // 按照priority优先级从小到大拆入
            int insertIndex = -1;
            for (int i = 0; i < this.Count; i++)
            {
                var r = this[i];
                if (element.priority < r.priority)
                {
                    this.Insert(i, element);
                    insertIndex = i;
                    break;
                }
            }
            if (insertIndex == -1)
            {
                insertIndex = this.Count;
                this.Add(element);
            }
            return insertIndex;
        }

    }
}
